<?php
declare (strict_types = 1);

namespace app\admin\service;
use app\admin\model\MenuModel;

class MenuService extends \think\Service
{
    /**
     * 注册服务
     *
     * @return mixed
     */
    public function register()
    {
    	//
    }

    /**
     * 执行服务
     *
     * @return mixed
     */
    public function boot()
    {
        //
    }

    /**
     * @param $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($params): \think\response\Json
    {
        $res = MenuModel::query()->page($params['pageNum'], $params['pageSize'])->select();
        return successMsg(data: $res);
    }

    /**
     * @param $params
     * @return \think\response\Json
     */
    public function create($params): \think\response\Json
    {
        $res = MenuModel::create($params);
        return successMsg(data: $res);
    }

    /**
     * @param $params
     * @return \think\response\Json
     */
    public function read($id): \think\response\Json
    {
        $res = MenuModel::find($id);
        return successMsg(data: $res);
    }

    /**
     * @param $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userMenu($user): \think\response\Json
    {
        $role = app(RoleService::class)->read($user['user_role']);

        $query = MenuModel::query();

        if($role['node']){
            $query = $query->whereIn('id' , $role['node']);
        }

        $menu = $query->select()->toArray();

        return successMsg(data:getTree($menu));
    }

}
